package com.fzn2._01greenhorn.class07;

/**
 * 测试链接：https://leetcode.com/problems/balanced-binary-tree
 * 110.   判断是否是平衡二叉树
 * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
 * 即是  |左数-右数| <= 1
 */
public class Code02_BalancedBinaryTree {

    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    // 以某个节点的时候 1）整个树是否平  2）整棵树的高度是什么
    public static class Info {
        public boolean isBalanced;
        public int height;

        public Info(boolean i, int h) {
            isBalanced = i;
            height = h;
        }
    }

    public static boolean isBalanced(TreeNode root) {
        return process(root).isBalanced;
    }

    public static Info process(TreeNode root) {
        if (root == null) {
            return new Info(true, 0);
        }
        // root !=null
        Info leftInfo = process(root.left);
        Info rightInfo = process(root.right);
        // 数的高度
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        // 平衡二叉树的条件  左边是平衡 右边是平衡 左-右 <=1
        boolean isBalanced = leftInfo.isBalanced && rightInfo.isBalanced
                && Math.abs(leftInfo.height - rightInfo.height) < 2;
        return new Info(isBalanced, height);
    }

}
